﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GTA.Web.Pages
{
    public partial class Tasks : BasePage
    {
        #region Starting Page
        protected void Page_Load(object sender, EventArgs e)
        {
            StartPage();
        }
        private void StartPage()
        {
            if (!IsPostBack)
            {
                LoadProjects();
                LoadCategories();
                LoadStates();
                if (GTAMasterPage.LoggedUser != null && GTAMasterPage.LoggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.User)
                {
                    LoadResponsibles(null);
                    lstProjects.AutoPostBack = false;
                }
                else
                    LoadNonSelectResponsibles();
            }
            GenerateScripts();
        }
        #endregion

        #region Events
        protected void lstProjects_SelectedIndexChanged(Object sender, EventArgs e)
        {
            SelectProject();
        }
        protected void cmdSearch_Click(Object sender, EventArgs e)
        {
            SearchScenarios();
        }
        protected void cmdClean_Click(Object sender, EventArgs e)
        {
            CleanFilter();
        }
        protected void ibFindScheduleStartFilterFrom_Click(Object sender, EventArgs e)
        {
            ShowCalendar(dvDtScheduleStartFrom, lblTitleStartFrom, "Período Início Previsto - DE");
        }
        protected void ibFindScheduleStartFilterTo_Click(Object sender, EventArgs e)
        {
            ShowCalendar(dvDtScheduleStartTo, lblTitleStartTo, "Período Início Previsto - ATÉ");
        }
        protected void ibFindScheduleEndFilterFrom_Click(Object sender, EventArgs e)
        {
            ShowCalendar(dvDtScheduleEndFrom, lblTitleEndFrom, "Período Término Previsto - DE");
        }
        protected void ibFindScheduleEndFilterTo_Click(Object sender, EventArgs e)
        {
            ShowCalendar(dvDtScheduleEndTo, lblTitleEndTo, "Período Término Previsto - ATÉ");
        }
        protected void dtScheduleStartFrom_SelectionChanged(Object sender, EventArgs e)
        {
            SetDateValue(dvDtScheduleStartFrom, dtScheduleStartFrom, txtFilterDateScheduleStartIni);
        }
        protected void dtScheduleStartTo_SelectionChanged(Object sender, EventArgs e)
        {
            SetDateValue(dvDtScheduleStartTo, dtScheduleStartTo, txtFilterDateScheduleStartEnd);
        }
        protected void dtScheduleEndFrom_SelectionChanged(Object sender, EventArgs e)
        {
            SetDateValue(dvDtScheduleEndFrom, dtScheduleEndFrom, txtFilterDateScheduleEndIni);
        }
        protected void dtScheduleEndTo_SelectionChanged(Object sender, EventArgs e)
        {
            SetDateValue(dvDtScheduleEndTo, dtScheduleEndTo, txtFilterDateScheduleEndEnd);
        }
        protected void ibClearDateStartFrom_Click(Object sender, EventArgs e)
        {
            ClearDateField(txtFilterDateScheduleStartIni);
        }
        protected void ibClearDateStartTo_Click(Object sender, EventArgs e)
        {
            ClearDateField(txtFilterDateScheduleStartEnd);
        }
        protected void ibClearDateEndFrom_Click(Object sender, EventArgs e)
        {
            ClearDateField(txtFilterDateScheduleEndIni);
        }
        protected void ibClearDateEndTo_Click(Object sender, EventArgs e)
        {
            ClearDateField(txtFilterDateScheduleEndEnd);
        }
        protected void rptScenarios_ItemDataBound(Object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                System.Web.UI.HtmlControls.HtmlTableRow ctrl = e.Item.FindControl("rowItem") as System.Web.UI.HtmlControls.HtmlTableRow;
                BusinessEntity.Task itemTask = e.Item.DataItem as BusinessEntity.Task;
                if (ctrl != null)
                {
                    //Status Finalizado
                    if (itemTask.State.Description.ToLowerInvariant().CompareTo("finalizado") == 0)
                    {
                        ctrl.Attributes["class"] = "RowItemFinished";
                    }
                    //Status Cancelado - Status == "Cancelado"
                    else if (itemTask.State.Description.ToLowerInvariant().CompareTo("cancelado") == 0)
                    {
                        ctrl.Attributes["class"] = "RowItemCanceled";
                    }
                    //Atraso na Entrega - Status != "Finalizado" e hoje > "Termino Previsto"
                    else if (itemTask.State.Description.ToLowerInvariant().CompareTo("finalizado") != 0 &&
                        DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedEnd.Date) > 0)
                    {
                        ctrl.Attributes["class"] = "RowItemDeliveryOverdue";
                    }
                    //Atraso no Início - "Início" não informado && "Início Previsto" <= hoje && Status != "Finalizado".
                    else if (itemTask.State.Description.ToLowerInvariant().CompareTo("finalizado") != 0 &&
                        itemTask.ScheduleRealizedStart == DateTime.MinValue &&
                        itemTask.ScheduleEstimatedStart.Date.CompareTo(DateTime.Now.Date) <= 0)
                    {
                        ctrl.Attributes["class"] = "RowItemStartOverdue";
                    }
                    //Alerta de Entrega - hoje <= ("Termino Previsto" - 4)
                    else if (itemTask.State.Description.ToLowerInvariant().CompareTo("finalizado") != 0 &&
                        DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedEnd.AddDays(-2).Date) >= 0 &&
                        DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedEnd.Date) <= 0)
                    {
                        ctrl.Attributes["class"] = "RowItemDeliveryAlert";
                    }
                    //Alerta de Início - "Início" não informado && hoje >= ("Início Previsto" - 4)
                    else if (itemTask.State.Description.ToLowerInvariant().CompareTo("finalizado") != 0 &&
                        itemTask.ScheduleRealizedStart == DateTime.MinValue &&
                        DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedStart.AddDays(-2).Date) >= 0 &&
                        DateTime.Now.Date.CompareTo(itemTask.ScheduleEstimatedStart.Date) <= 0)
                    {
                        ctrl.Attributes["class"] = "RowItemStartAlert";
                    }
                }
            }
        }
        #endregion

        #region Methods
        private void ClearDateField(TextBox txtFilterDate)
        {
            txtFilterDate.Text = String.Empty;
        }
        private void SetDateValue(System.Web.UI.HtmlControls.HtmlGenericControl div, Calendar dtDate, TextBox txtDate)
        {
            txtDate.Text = dtDate.SelectedDate.ToString(DATE_FORMAT);
            div.Visible = false;
        }
        private void ShowCalendar(System.Web.UI.HtmlControls.HtmlGenericControl div, Label lblTitle, string title)
        {
            div.Visible = true;
            lblTitle.Text = title;
        }
        private void GenerateScripts()
        {
            txtTaskID.Attributes.Add("onkeypress", "return SomenteNumero(event);");
        }
        private void LoadNonSelectResponsibles()
        {
            lstResponsibles.Items.Clear();
            lstResponsibles.Items.Add("Selecione o Projeto");
            lstResponsibles.Enabled = false;
        }
        private void LoadProjects()
        {
            try
            {
                lstProjects.Items.Clear();
                if (GTAMasterPage.LoggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.Master)
                {
                    if (Global.Projects != null && Global.Projects.Count > 0)
                    {
                        foreach (BusinessEntity.Project itemProject in Global.Projects)
                            lstProjects.Items.Add(new ListItem() { Value = itemProject.Name, Text = itemProject.Name });
                    }
                }
                else
                    GTAMasterPage.LoggedUser.UserProjects.ForEach(item => lstProjects.Items.Add(new ListItem() { Value = item.Name, Text = item.Name }));
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de projetos", ex);
            }
        }
        private void LoadCategories()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> categories = bl.ListCategories();
                if (categories != null)
                    categories.ForEach(item => lstCategories.Items.Add(new ListItem() { Value = item.ID.ToString(), Text = item.Description }));
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de categorias", ex);
            }
        }
        private void LoadStates()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> states = bl.ListStates();
                if (states != null)
                    states.ForEach(item => lstStates.Items.Add(new ListItem() { Value = item.ID.ToString(), Text = item.Description }));

            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de status", ex);
            }
        }
        private void SelectProject()
        {
            LoadResponsibles(GetSelectedProjects());
        }
        private void LoadResponsibles(List<BusinessEntity.Project> selectedProjects)
        {
            try
            {
                lstResponsibles.Items.Clear();
                if (GTAMasterPage.LoggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.Master)
                {
                    if (selectedProjects != null && selectedProjects.Count > 0)
                    {
                        List<BusinessEntity.UserManagement.User> selectedItems = GetSelectedResponsibles();

                        BusinessLogic.GTA bl = new BusinessLogic.GTA();
                        selectedProjects = GetSelectedProjects();
                        List<BusinessEntity.UserManagement.User> users = bl.ListUsers(selectedProjects);
                        if (users != null && users.Count > 0)
                            users.ForEach(item => lstResponsibles.Items.Add(new ListItem(item.Name, item.Name)));

                        if (selectedItems != null && selectedItems.Count > 0)
                        {
                            foreach (BusinessEntity.UserManagement.User itemSelected in selectedItems)
                            {
                                foreach (ListItem listItem in lstResponsibles.Items)
                                {
                                    if (listItem.Value.CompareTo(itemSelected.Name) == 0)
                                    {
                                        listItem.Selected = true;
                                        break;
                                    }
                                }
                            }
                        }
                        lstResponsibles.Enabled = true;
                    }
                    else
                        LoadNonSelectResponsibles();
                }
                else
                {
                    lstResponsibles.Items.Add(new ListItem(GTAMasterPage.LoggedUser.Name, GTAMasterPage.LoggedUser.Name));
                    lstResponsibles.Items[0].Selected = true;
                    lstResponsibles.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de responsávels", ex);
            }
        }
        private BusinessEntity.TaskFilter GetSearchFilter()
        {
            BusinessEntity.TaskFilter filter = new GTA.BusinessEntity.TaskFilter();
            if (!String.IsNullOrEmpty(txtTaskID.Text))
                filter.ID = Convert.ToInt32(txtTaskID.Text);
            if (!String.IsNullOrEmpty(txtFilterDateScheduleEndIni.Text))
                filter.ScheduleEstimatedEndFrom = Convert.ToDateTime(txtFilterDateScheduleEndIni.Text);
            if (!String.IsNullOrEmpty(txtFilterDateScheduleEndEnd.Text))
                filter.ScheduleEstimatedEndTo = Convert.ToDateTime(txtFilterDateScheduleEndEnd.Text);
            if (!String.IsNullOrEmpty(txtFilterDateScheduleStartIni.Text))
                filter.ScheduleEstimatedStartFrom = Convert.ToDateTime(txtFilterDateScheduleStartIni.Text);
            if (!String.IsNullOrEmpty(txtFilterDateScheduleStartEnd.Text))
                filter.ScheduleEstimatedStartTo = Convert.ToDateTime(txtFilterDateScheduleStartEnd.Text);
            filter.Project = GetSelectedProjects();
            filter.DesignedTo = GetSelectedResponsibles();
            filter.Category = GetSelectedCategories();
            filter.State = GetSelectedStates();
            return filter;
        }
        private List<BusinessEntity.Project> GetSelectedProjects()
        {
            List<BusinessEntity.Project> selectedProjects = new List<GTA.BusinessEntity.Project>();
            if (Global.Projects != null && Global.Projects.Count > 0)
            {
                foreach (ListItem listItem in lstProjects.Items)
                {
                    if (listItem.Selected)
                        selectedProjects.Add(Global.Projects.Find(item => item.Name.CompareTo(listItem.Text) == 0));
                }
            }
            return selectedProjects;
        }
        private List<BusinessEntity.TaskDomain> GetSelectedStates()
        {
            List<BusinessEntity.TaskDomain> states = new List<GTA.BusinessEntity.TaskDomain>();
            foreach (ListItem item in lstStates.Items)
            {
                if (item.Selected)
                    states.Add(new GTA.BusinessEntity.TaskDomain(Convert.ToInt32(item.Value), item.Text));
            }
            return states;
        }
        private List<BusinessEntity.TaskDomain> GetSelectedCategories()
        {
            List<BusinessEntity.TaskDomain> categories = new List<GTA.BusinessEntity.TaskDomain>();
            foreach (ListItem item in lstCategories.Items)
            {
                if (item.Selected)
                    categories.Add(new GTA.BusinessEntity.TaskDomain(Convert.ToInt32(item.Value), item.Text));
            }
            return categories;
        }
        private List<BusinessEntity.UserManagement.User> GetSelectedResponsibles()
        {
            List<BusinessEntity.UserManagement.User> users = new List<GTA.BusinessEntity.UserManagement.User>();
            if (((GTAMaster)Master).LoggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.Master)
            {
                foreach (ListItem item in lstResponsibles.Items)
                {
                    if (item.Selected)
                        users.Add(new GTA.BusinessEntity.UserManagement.User(item.Text));
                }
            }
            else
                users.Add(((GTAMaster)Master).LoggedUser);
            return users;
        }
        private void SearchScenarios()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                BusinessEntity.TaskFilter filter = GetSearchFilter();
                List<BusinessEntity.Task> list = bl.ListArchitectureTasks(filter, GTAMasterPage.LoggedUser);
                rptScenarios.DataSource = list;
                rptScenarios.DataBind();
                if (list == null || list.Count == 0)
                    ShowMessage("Nenhum retorno!", GTA.Web.UserControls.ucMessage.MessageType.Alert);

                lblQtdTasks.Text = list != null ? list.Count.ToString() : "0";
            }
            catch (Exception ex)
            {
                HandleException("Pesquisa cenários de Arquitetura", ex);
            }
        }
        private void CleanFilter()
        {
            try
            {
                txtTaskID.Text = String.Empty;
                ClearListSelectedItems(lstCategories);
                ClearListSelectedItems(lstProjects);
                if (GTAMasterPage.LoggedUser.UserProfile == BusinessEntity.UserManagement.Profiler.Master)
                    LoadNonSelectResponsibles();
                ClearListSelectedItems(lstStates);
                txtFilterDateScheduleStartIni.Focus();
            }
            catch (Exception ex)
            {
                HandleException("Clean search filter", ex);
            }
        }
        private void ClearListSelectedItems(ListBox list)
        {
            foreach (ListItem item in list.Items)
                item.Selected = false;
        }
        #endregion
    }
}
